<template>
  <div>
    <el-upload
      ref="upload"
      action="https://up-z2.qiniup.com"
      multiple
      :show-file-list="false"
      :data="{}"
      :file-list="uploads"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-error="handleError"
      :on-remove="handleRemove"
    >
      <el-button slot="trigger" type="primary" size="small">添加文件</el-button>
    </el-upload>
    <div>
      <uploads-list-item
        v-for="upload in uploads"
        :key="upload.uid"
        :file="upload"
        @remove="abortUpload"
        @handleTags="handleTags"
      />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import UploadsListItem from '@/views/documents/components/uploads-list/list-item';

export default {
  name: 'upload-doc',
  components: {
    UploadsListItem,
  },
  props: {
    uploads: {
      type: Array,
      required: true,
    },
    limitSize: { // 上传限制 { size: 204800, msg: '错误信息' } 单位是 字节(b)
      type: Object,
      default: null,
    },
  },
  computed: {
    ...mapState({ preUploads: 'preUploads' }),
  },
  mounted() {
    this.$refs.upload.uploadFiles = this.preUploads; // 更新到组件内
    this.$emit('update:uploads', this.preUploads); // 更新到显示
    this.$refs.upload.submit();
  },
  destroyed() {
    this.clearUploads();
  },
  methods: {
    ...mapActions({ clearUploads: 'setPreUploads' }),
    // 获取上传密钥
    getUploadToken() {
      return new Promise((resolve, reject) => {
        this.$api.other.uploadToken()
          .then(res => resolve(res.data.token))
          .catch((err) => {
            this.$message.error('获取上传密钥失败', err);
            reject(err);
          });
      });
    },
    // 上传前添加必要的上传密钥等信息
    async beforeUpload(file) {
      if (this.limitSize && file.size > this.limitSize.size) { // 限制大小
        this.$message.error(this.limitSize.msg);
        return false;
      }
      const uploadToken = await this.getUploadToken();
      return Object.assign(this.$refs.upload.data, {
        token: uploadToken,
        key: `uploads-${new Date().getTime()}/${file.name}`,
        'x:user_id': this.$store.state.currentUser.id,
      });
    },
    // 文件列表变化
    handleChange(file, fileList) {
      fileList.map((f) => {
        if (f.status === 'success') Object.assign(f, { tags: [] });
        return f;
      });
      this.$emit('update:uploads', fileList.map(i => Object.assign({}, i, {
        ext: i.ext || i.name.substr(i.name.lastIndexOf('.') + 1),
        name: i.ext ? i.name : i.name.substring(0, i.name.lastIndexOf('.')),
      })));
    },
    // 上传失败
    handleError(err) { this.$message.error(`上传失败 ${err}`); },
    // 移出列表
    handleRemove(file, fileList) { this.$emit('update:uploads', fileList); },
    // 取消上传
    abortUpload(file) { this.$refs.upload.handleRemove(file); },
    // 打标签
    handleTags(obj) { this.$emit('handleTags', obj); },
  },
};
</script>

<style></style>
